package org.jeecg.modules.mail.service.impl;

import org.jeecg.common.api.dto.message.TemplateDTO;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.mail.VerificationCodeUtil;
import org.jeecg.modules.mail.service.IMailService;
import org.jeecg.modules.mail.entity.Mail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;

@Service
@Async
public class MailServiceImpl implements IMailService {

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private ISysBaseAPI iSysBaseAPI;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void send(Mail mail) {

        System.err.println(javaMailSender);

        SimpleMailMessage message = new SimpleMailMessage();

        message.setFrom("2217530085@qq.com");
        message.setTo(mail.getUsername());
        message.setSubject(mail.getTitle());
        message.setText(mail.getContent());
        javaMailSender.send(message);
    }

    @Override
    public void sendVerificationCode(String email) throws MessagingException {
        String key = "email:" + email + ":verification_code";
        if (redisUtil.get(key) != null) {
            return;
        }

        TemplateDTO dto = new TemplateDTO();
        String code = VerificationCodeUtil.getVerificationCode();
        dto.setTemplateCode("verification_code");
        Map<String,String> map = new HashMap<>();
        map.put("verification_code",code);
        dto.setTemplateParam(map);
        String content = iSysBaseAPI.parseTemplateByCode(dto);

        //将验证码写入缓存


        redisUtil.set(key,code,30 * 60);

        MimeMessage message = javaMailSender.createMimeMessage();
        message.setFrom("2217530085@qq.com");
        message.setSubject("验证码");
        message.setRecipients(Message.RecipientType.TO, "2217530085@qq.com");
        message.setText(content,"UTF-8","HTML");
        javaMailSender.send(message);
    }
}
